package action;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import table.EvalHandle;
import table.EvaluationEvent;
import table.User;

/**
 * 添加一个空的评价活动，系统自动分配评价活动的id
 * 参数：无
 * 使用页面：admin_ee_manage_main.jsp
 */
@WebServlet("/ChangeStatus")
public class ChangeStatus extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	 public ChangeStatus() {
	        super();
	    }
	 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			// 管理员登录有效性验证段
			User user = (User) request.getSession().getAttribute("user");
			if(user == null || !user.getGroup().equals("admin")){
				request.getRequestDispatcher("index.jsp").forward(request, response);
				return;
			}
			
			// 响应设置段
			response.setContentType("text/xml; charset=UTF-8");
			response.setHeader("Cache-Control","no-store");
			response.setHeader("Pragma","no-cache");
			response.setDateHeader("Expires",0);
			
			String seeid = request.getParameter("eeid");
			if(seeid == null || seeid.isEmpty()) {
				response.getWriter().print("<root><result>wrong parameter</result></root>");
				return;
			}
			int eeid = 0;
			try {
				eeid = Integer.parseInt(seeid);
			} catch (Exception e) {
				response.getWriter().print("<root><result>wrong parameter</result></root>");
				return;
			}
			
			String status = request.getParameter("status");
			if(status == null || status.isEmpty()) {
				response.getWriter().print("<root><result>wrong parameter</result></root>");
				return;
			}
			
			if( !(EvaluationEvent.INIT.equals(status) || EvaluationEvent.PREPARE.equals(status)
				|| EvaluationEvent.AVAILABLE.equals(status) || EvaluationEvent.PAUSE.equals(status)
				|| EvaluationEvent.STOP.equals(status))) {
				response.getWriter().print("<root><result>No such status</result></root>");
				return;
			};
			
			EvalHandle h = new EvalHandle();
			EvaluationEvent ee = h.getEeById(eeid);
			if(ee == null) {
				response.getWriter().print("<root><result>No such ee</result></root>");
				return;
			}
			
			ee.setStatus(status);
			if(h.updateEeToDB(ee.getId(), ee)) {
				response.getWriter().print("<root><result>OK</result><status>" + ee.getStatus() + "</status></root>");
			}else{
				response.getWriter().print("<root><result>FAIL</result><status>" + ee.getStatus() + "</status></root>");
			};
		}

		/**
		 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
		 */
		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doGet(request, response);
		}
}